package cn.bonoon.handler.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import cn.bonoon.core.plugins.LoginService;
import cn.bonoon.entities.plugins.AccountEntity;
import cn.bonoon.entities.plugins.FlagType;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.support.entities.EntityOwner;
import cn.bonoon.kernel.util.StringHelper;

public class UserDetailsHandlerImpl implements UserDetailsService {

	private static final Logger log = LoggerFactory.getLogger(UserDetailsHandlerImpl.class);

	private final LoginService loginService;
//	private final ModuleManager moduleManager;

	@Autowired
	public UserDetailsHandlerImpl(LoginService loginService) {
		this.loginService = loginService;
//		this.moduleManager = moduleManager;
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		AccountEntity user = loginService.loadByLoginName(username);
		if (null == user || !user.getLoginName().equals(username)) {
			log.info("找不到用户：{}", username);
			throw new UsernameNotFoundException(username + " 找不到该用户！");
		}
		Long uid = user.getId();
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		List<String> tmpRoles = new ArrayList<String>();
		for (String role : loginService.getRoleKeys(uid)) {
			StringHelper.toList(tmpRoles, role);
		}
		FlagType flag = user.getFlag();
		if (tmpRoles.isEmpty()) {
			if (flag == FlagType.SUPER){
				// 超级管理员
				authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
			}
		} else {
			for (String r : tmpRoles) {
				authorities.add(new SimpleGrantedAuthority(r));
			}
		}
		String password = user.getLoginPwd();
		boolean enabled = user.getStatus() == AccountEntity.NORMAL;
		
		long owner;
		if(EntityOwner.class.isAssignableFrom(user.getClass())){
			owner = user.getId();
		}else{
			owner = user.getOwnerId();
		}
		
//		String targetMenu;
//		if(flag == FlagType.CUSTOM || flag == FlagType.GUEST){
//			targetMenu = moduleManager.getDefaultEndpoint();
//		}else{
//			targetMenu= moduleManager.getEndpoint();
//		}
		String name = user.getName();
		boolean fcpwd = user.isForcedChangePwd();
		LogonUser lu = new LogonUser(uid, username, password, enabled, authorities, owner);
		return lu.initPrivileges(name, fcpwd, flag);
	}
}
